#include "logger.h"
#include "tools/m_sleep.h"
#include "version.h"
#include <sys/stat.h>

std::string Logger::configM     = std::string(APP_NAME) + std::string(".zconf");
std::string Logger::nameM       = APP_NAME;
Logger*   Logger::instanceM     = nullptr;
MMutex    Logger::instanceLockM;

Logger* Logger::getInstance()
{
    if (instanceM == nullptr)
    {
        AUTO_GUARD(gd, MMutex, instanceLockM);
        if (instanceM == nullptr)
        {
            instanceM = new Logger();
        }
    }

    return instanceM;
}

Logger::Logger()
{
    /* zlog初始化 */
    if (dzlog_init_ex(configM.c_str(), nameM.c_str()))
    {
        printf("zlog init failed\n");
        exit(-1);
    }

    struct stat tmpStat;
    if (stat(configM.c_str(), &tmpStat) == 0)
    {
        log_error("zlog stat failed, please check %s\n", configM.c_str());
        printf("zlog stat failed\n");
    }

    lastConfigTimeM.tv_sec = tmpStat.st_mtim.tv_sec;
    lastConfigTimeM.tv_nsec = tmpStat.st_mtim.tv_nsec;
}

Logger::~Logger()
{

}

void Logger::reload()
{
    //每十秒检测一次
    uint64_t curTime = getMilliseconds();
    if ((lastCheckTimeM + (10 * 1000)) < curTime)
    {
        lastCheckTimeM = curTime;

        struct stat tmpStat;
        std::string path = std::string("/userdata/dgri/zlog.d/") + configM;
        if (stat(path.c_str(), &tmpStat) != 0)
        {
            log_error("Get zlog stat error!!!");
            return;
        }

        if ((lastConfigTimeM.tv_sec == tmpStat.st_mtim.tv_sec) &&
            (lastConfigTimeM.tv_nsec == tmpStat.st_mtim.tv_nsec))
        {
            return;
        }

        lastConfigTimeM.tv_sec = tmpStat.st_mtim.tv_sec;
        lastConfigTimeM.tv_nsec = tmpStat.st_mtim.tv_nsec;

        dzlog_reload(configM.c_str());
    }
}